package org.zjx.task;

import org.zjx.core.GameInstance;
import org.zjx.core.GameThread;
import org.zjx.state.StateManager;
import org.zjx.task.core.TaskScheduler;
import org.zjx.task.exception.TaskExecutionException;
import org.zjx.window.GameWindow;

public abstract class InitCompleteTask extends RetryTask {
    protected GameInstance gameInstance;
    protected GameThread gameThread;
    protected StateManager stateManager;
    protected GameWindow gameWindow;

    public InitCompleteTask(String taskId) {
        super(taskId);
        this.failureStrategy = FailureStrategy.STOP;
    }

    public void init(TaskScheduler scheduler) {
        gameInstance = scheduler.getGameInstance();
        gameThread = gameInstance.getGameThread();
        gameWindow = gameThread.getWindow();
        stateManager = gameThread.getGameContext().getStateManager();
        setMaxRetries(10);
    }

    public abstract boolean complete();

    public void run(ChainContext context, TaskScheduler scheduler) throws TaskExecutionException {
        this.setStatus(TaskStatus.RUNNING);
        System.out.println("执行任务:" + this.getTaskId());
        try {
            init(scheduler);
            if (!complete()) {
                this.execute(context, scheduler);
            }
            System.out.println("执行任务:" + this.getTaskId() + "完成！");
            this.setStatus(TaskStatus.SUCCESS);
        } catch (InterruptedException e) {
            this.setStatus(TaskStatus.INTERRUPTED);
            Thread.currentThread().interrupt();
            throw new TaskExecutionException("Task interrupted", e);
        } catch (Exception e) {
            this.setStatus(TaskStatus.FAILED);
            throw new TaskExecutionException("Task execution failed: " + e.getMessage(), e);
        }
    }

}
